"""
word 转pdf  电脑需要提前安装office
"""
import os
from win32com import client


def get_path():
    path = os.getcwd()
    filename_list = os.listdir(path)
    pdfdir = os.path.join(path, "pdf")
    # 当前目录下生产pdf文件夹
    if not os.path.exists(pdfdir):
        os.makedirs(pdfdir)

    wordname_list = [
        filename for filename in filename_list if filename.endswith((".doc", ".docx"))]

    for wordname in wordname_list:
        pdfname = os.path.splitext(wordname)[0] + ".pdf"
        # 拼接 路径和文件名
        wordpath = os.path.join(path, wordname)
        pdfpath = os.path.join(pdfdir, pdfname)
        # yield 生成器
        yield wordpath, pdfpath


def convert_word_to_pdf():
    word = client.Dispatch("Word.Application")
    word.Visible = 0
    for wordpath, pdfpath in get_path():
        print(">>:", wordpath, "开始转换pdf...")
        newpdf = word.Documents.Open(wordpath)
        newpdf.SaveAs(pdfpath, FileFormat=17)
        newpdf.Close()
        print(">>:", wordpath, "转换完成")


if __name__ == "__main__":
    convert_word_to_pdf()
